package main

import (
	"context"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"log"
	"menu-generation-go/config"
	"menu-generation-go/database"
	"menu-generation-go/models"
	"menu-generation-go/routers"
	"menu-generation-go/utils"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"
)

func main() {
	// 加载配置
	cfg, err := config.LoadConfig("config.toml")
	if err != nil {
		log.Fatalf("Failed to load config: %v", err)
	}

	// 初始化数据库连接
	db, err := database.NewDatabase(&cfg.Database)
	if err != nil {
		log.Fatalf("Failed to initialize database: %v", err)
	}
	defer db.Close()

	// 设置Gin模式
	if cfg.Database.LogLevel == "silent" {
		gin.SetMode(gin.ReleaseMode)
	}
	// 初始化路由
	router := routers.SetupRouter(db)

	// 创建HTTP服务器
	srv := &http.Server{
		Addr:    ":" + utils.IntToStr(cfg.Server.Port),
		Handler: router,
	}
	// 111
	// 在goroutine中启动服务器
	go func() {
		log.Printf("Server is running on http://localhost%s", srv.Addr)
		if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			log.Fatalf("listen: %s\n", err)
		}
	}()
	//go data(db.DB)
	// 等待中断信号以优雅地关闭服务器
	quit := make(chan os.Signal, 1)
	// signal.Notify(quit, os.Interrupt) // 仅捕获中断信号
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM) // 捕获中断和终止信号
	<-quit
	log.Println("Shutting down server...")

	// 创建一个5秒超时的上下文
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()

	// 优雅关闭服务器
	if err := srv.Shutdown(ctx); err != nil {
		log.Fatal("Server forced to shutdown:", err)
	}

	log.Println("Server exiting")
}

// Recipe 对应 JSON 中的菜谱结构
type Recipe struct {
	Name        string   `json:"name"`
	URL         string   `json:"url"`
	Ingredients []string `json:"ingredients"`
	Page        int      `json:"page"`
}

func data(db *gorm.DB) {
	// 1. 读取 JSON 文件
	fileContent, err := os.ReadFile("jiachang.json")
	if err != nil {
		log.Fatalf("Error reading JSON file: %v", err)
	}

	// 2. 解析 JSON
	var recipes []Recipe
	err = json.Unmarshal(fileContent, &recipes)
	if err != nil {
		log.Fatalf("Error unmarshaling JSON: %v", err)
	}

	// 5. 遍历菜谱并插入数据库
	for _, recipe := range recipes {
		// 将配料数组转换为逗号分隔的字符串
		ingredientsStr := ""
		for j, ing := range recipe.Ingredients {
			if j > 0 {
				ingredientsStr += ","
			}
			ingredientsStr += ing
		}

		var r models.MenuRecipe
		r.Name = recipe.Name
		r.Ingredients = ingredientsStr
		r.Type = 4

		db.Where("name = ?", recipe.Name).First(&r)
		if r.ID == 0 {
			db.Create(&r)
		}

	}
}
